"""
Author: Meng
Date: 2018/7/23
"""
from flask_restful import Resource, reqparse, fields, marshal_with
from app.api import api
from app.models.admin.user import User, UserAvatar
from app.models.admin.config import FConfig
from f_lib.code import Msg
from f_lib.tool.email import send_email_html, send_email_html_executor
from f_lib.principal.safety import safety_strategy
from concurrent.futures import ThreadPoolExecutor

executor = ThreadPoolExecutor()


class SendEmail(Resource):
    parse = reqparse.RequestParser()
    parse.add_argument('key', type=str, required=True)
    parse.add_argument('receiver', type=str, required=True)
    parse.add_argument('content', type=str, required=True)
    parse.add_argument('title', type=str)

    @safety_strategy
    def get(self):
        arg = self.parse.parse_args()

        config = FConfig.query_one()
        email_admin = config.email_info
        key = config.app_secret
        if key == arg['key']:
            title = arg['title']
            content = arg['content']
            rec = arg['receiver']
            if title is None:
                title = content[:10] + '...'
            # send_stat = send_email_html(email_admin, receiver=rec, title=title, mail_msg=content)
            executor.submit(send_email_html_executor, admin=email_admin, receiver=rec, title=title, mail_msg=content)
            # if send_stat:
            return Msg.success()

            # return Msg.failed_dict(6000)
        else:
            return Msg.failed_dict(403)


api.add_resource(SendEmail, '/send_email', endpoint='send_email')
